package com.example.cinemasystemv2.controller;

import com.example.cinemasystemv2.entity.*;
import com.example.cinemasystemv2.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/manager")
public class ManagerController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private MovieService movieService;
    
    @Autowired
    private ScreeningService screeningService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private SystemLogService systemLogService;
    
    @Autowired
    private TicketService ticketService;
    
    @Autowired
    private ScreeningRoomService screeningRoomService;
    
    @Autowired
    private SnackService snackService;
    
    // 检查经理权限
    private boolean checkManagerRole(HttpSession session) {
        String role = (String) session.getAttribute("role");
        return "manager".equals(role);
    }
    
    private void addCurrentUserToModel(Model model, HttpSession session) {
        String username = (String) session.getAttribute("username");
        User currentUser = userService.getUserByUsername(username).orElse(null);
        model.addAttribute("currentUser", currentUser);
    }
    
    // 经理仪表板
    @GetMapping("/dashboard")
    public String dashboard(Model model, HttpSession session) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        // 添加统计数据
        model.addAttribute("totalMovies", movieService.getAllMovies().size());
        model.addAttribute("totalScreenings", screeningService.getAllScreenings().size());
        model.addAttribute("todayScreenings", screeningService.getTodayScreenings().size());
        
        // 今日销售数据
        List<Order> todayOrders = orderService.getTodayOrders();
        double todaySales = todayOrders.stream()
            .filter(order -> !order.isRefunded())
            .mapToDouble(Order::getAmount)
            .sum();
        model.addAttribute("todaySales", todaySales);
        model.addAttribute("todayTickets", todayOrders.size());
        
        return "manager/dashboard";
    }
    
    // 影片管理页面
    @GetMapping("/movies")
    public String movieManagement(Model model, HttpSession session) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        model.addAttribute("movies", movieService.getAllMovies());
        
        return "manager/movies";
    }
    
    // 添加影片
    @PostMapping("/movies/add")
    public String addMovie(@RequestParam String title,
                          @RequestParam String director,
                          @RequestParam String actors,
                          @RequestParam String synopsis,
                          @RequestParam int duration,
                          @RequestParam double rating,
                          @RequestParam(required = false) String status,
                          HttpSession session,
                          RedirectAttributes redirectAttributes) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        try {
            Movie movie = new Movie();
            movie.setTitle(title);
            movie.setDirector(director);
            movie.setActors(actors);
            movie.setSynopsis(synopsis);
            movie.setDuration(duration);
            movie.setRating(rating);
            movie.setStatus(status != null ? status : "未上映");
            
            movieService.saveMovie(movie);
            
            String managerUsername = (String) session.getAttribute("username");
            systemLogService.log("添加影片: " + title, managerUsername, "ADD_MOVIE");
            
            redirectAttributes.addFlashAttribute("success", "影片添加成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "添加影片失败: " + e.getMessage());
        }
        
        return "redirect:/manager/movies";
    }
    
    // 编辑影片页面
    @GetMapping("/movies/edit/{movieId}")
    public String editMoviePage(@PathVariable Long movieId, Model model, HttpSession session) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        Optional<Movie> movieOpt = movieService.getMovieById(movieId);
        if (movieOpt.isPresent()) {
            model.addAttribute("movie", movieOpt.get());
            return "manager/edit-movie";
        } else {
            return "redirect:/manager/movies";
        }
    }
    
    // 更新影片信息
    @PostMapping("/movies/edit")
    public String updateMovie(@RequestParam Long movieId,
                             @RequestParam String title,
                             @RequestParam String director,
                             @RequestParam String actors,
                             @RequestParam String synopsis,
                             @RequestParam int duration,
                             @RequestParam double rating,
                             @RequestParam(required = false) String status,
                             HttpSession session,
                             RedirectAttributes redirectAttributes) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        try {
            Optional<Movie> movieOpt = movieService.getMovieById(movieId);
            if (movieOpt.isPresent()) {
                Movie movie = movieOpt.get();
                movie.setTitle(title);
                movie.setDirector(director);
                movie.setActors(actors);
                movie.setSynopsis(synopsis);
                movie.setDuration(duration);
                movie.setRating(rating);
                movie.setStatus(status != null ? status : "未上映");
                
                movieService.saveMovie(movie);
                
                String managerUsername = (String) session.getAttribute("username");
                systemLogService.log("修改影片信息: " + title, managerUsername, "UPDATE_MOVIE");
                
                redirectAttributes.addFlashAttribute("success", "影片信息更新成功");
            } else {
                redirectAttributes.addFlashAttribute("error", "影片不存在");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新影片失败: " + e.getMessage());
        }
        
        return "redirect:/manager/movies";
    }
    
    // 删除影片
    @PostMapping("/movies/delete/{movieId}")
    public String deleteMovie(@PathVariable Long movieId,
                             HttpSession session,
                             RedirectAttributes redirectAttributes) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        try {
            Optional<Movie> movieOpt = movieService.getMovieById(movieId);
            if (movieOpt.isPresent()) {
                Movie movie = movieOpt.get();
                
                // 检查是否有正在上映的排片
                List<Screening> activeScreenings = screeningService.getScreeningsByMovieId(movieId)
                    .stream()
                    .filter(screening -> screening.getStartTime().isAfter(LocalDateTime.now()))
                    .collect(Collectors.toList());
                
                if (!activeScreenings.isEmpty()) {
                    redirectAttributes.addFlashAttribute("error", "该影片正在上映中，无法删除");
                } else {
                    movieService.deleteMovie(movieId);
                    
                    String managerUsername = (String) session.getAttribute("username");
                    systemLogService.log("删除影片: " + movie.getTitle(), managerUsername, "DELETE_MOVIE");
                    
                    redirectAttributes.addFlashAttribute("success", "影片删除成功");
                }
            } else {
                redirectAttributes.addFlashAttribute("error", "影片不存在");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除影片失败: " + e.getMessage());
        }
        
        return "redirect:/manager/movies";
    }
    
    // 影片搜索
    @GetMapping("/movies/search")
    public String searchMovies(@RequestParam(required = false) String title,
                              @RequestParam(required = false) String director,
                              @RequestParam(required = false) String actors,
                              Model model, HttpSession session) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        List<Movie> movies;
        if ((title == null || title.trim().isEmpty()) && 
            (director == null || director.trim().isEmpty()) && 
            (actors == null || actors.trim().isEmpty())) {
            movies = movieService.getAllMovies();
        } else {
            movies = movieService.searchMoviesByMultipleFields(title, director, actors);
        }
        
        model.addAttribute("movies", movies);
        model.addAttribute("searchTitle", title);
        model.addAttribute("searchDirector", director);
        model.addAttribute("searchActors", actors);
        
        return "manager/movies";
    }
    
    // 排片管理页面
    @GetMapping("/screenings")
    public String screeningManagement(@RequestParam(defaultValue = "today") String period, 
                                     Model model, HttpSession session) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        // 根据period参数筛选场次
        List<Screening> screenings;
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime;
        LocalDateTime endTime;
        
        switch (period) {
            case "today":
                startTime = now.toLocalDate().atStartOfDay();
                endTime = now.toLocalDate().atTime(23, 59, 59);
                break;
            case "3days":
                startTime = now.toLocalDate().atStartOfDay();
                endTime = now.plusDays(3).toLocalDate().atTime(23, 59, 59);
                break;
            case "week":
                startTime = now.toLocalDate().atStartOfDay();
                endTime = now.plusDays(7).toLocalDate().atTime(23, 59, 59);
                break;
            default:
                startTime = now.toLocalDate().atStartOfDay();
                endTime = now.toLocalDate().atTime(23, 59, 59);
                period = "today";
        }
        
        screenings = screeningService.getScreeningsByDateRange(startTime, endTime);
        
        model.addAttribute("screenings", screenings);
        model.addAttribute("movies", movieService.getAllMovies());
        model.addAttribute("rooms", screeningRoomService.getAllRooms());
        model.addAttribute("period", period);
        
        return "manager/screenings";
    }
    
    // 添加场次
    @PostMapping("/screenings/add")
    public String addScreening(@RequestParam Long movieId,
                              @RequestParam Long roomId,
                              @RequestParam String startTime,
                              @RequestParam double price,
                              @RequestParam(defaultValue = "today") String period,
                              HttpSession session,
                              RedirectAttributes redirectAttributes) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        try {
            LocalDateTime dateTime = LocalDateTime.parse(startTime);
            
            Optional<Movie> movieOpt = movieService.getMovieById(movieId);
            Optional<ScreeningRoom> roomOpt = screeningRoomService.getRoomById(roomId);
            
            if (!movieOpt.isPresent() || !roomOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "电影或放映厅不存在");
                return "redirect:/manager/screenings?period=" + period;
            }
            
            Screening screening = new Screening();
            screening.setMovie(movieOpt.get());
            screening.setRoom(roomOpt.get());
            screening.setStartTime(dateTime);
            screening.setPrice(price);
            
            screeningService.saveScreening(screening);
            
            String managerUsername = (String) session.getAttribute("username");
            systemLogService.log("添加场次: " + movieOpt.get().getTitle(), managerUsername, "ADD_SCREENING");
            
            redirectAttributes.addFlashAttribute("success", "场次添加成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "添加场次失败: " + e.getMessage());
        }
        
        return "redirect:/manager/screenings?period=" + period;
    }
    
    // 编辑场次
    @PostMapping("/screenings/edit")
    public String updateScreening(@RequestParam Long screeningId,
                                 @RequestParam Long movieId,
                                 @RequestParam Long roomId,
                                 @RequestParam String startTime,
                                 @RequestParam double price,
                                 @RequestParam(defaultValue = "today") String period,
                                 HttpSession session,
                                 RedirectAttributes redirectAttributes) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        try {
            Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
            if (!screeningOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "场次不存在");
                return "redirect:/manager/screenings?period=" + period;
            }
            
            LocalDateTime dateTime = LocalDateTime.parse(startTime);
            
            Optional<Movie> movieOpt = movieService.getMovieById(movieId);
            Optional<ScreeningRoom> roomOpt = screeningRoomService.getRoomById(roomId);
            
            if (!movieOpt.isPresent() || !roomOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "电影或放映厅不存在");
                return "redirect:/manager/screenings?period=" + period;
            }
            
            Screening screening = screeningOpt.get();
            screening.setMovie(movieOpt.get());
            screening.setRoom(roomOpt.get());
            screening.setStartTime(dateTime);
            screening.setPrice(price);
            
            screeningService.updateScreening(screening);
            
            String managerUsername = (String) session.getAttribute("username");
            systemLogService.log("修改场次: " + movieOpt.get().getTitle(), managerUsername, "UPDATE_SCREENING");
            
            redirectAttributes.addFlashAttribute("success", "场次修改成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "修改场次失败: " + e.getMessage());
        }
        
        return "redirect:/manager/screenings?period=" + period;
    }
    
    // 删除场次
    @PostMapping("/screenings/delete")
    public String deleteScreening(@RequestParam Long screeningId,
                                 @RequestParam(defaultValue = "today") String period,
                                 HttpSession session,
                                 RedirectAttributes redirectAttributes) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        try {
            Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
            if (!screeningOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "场次不存在");
                return "redirect:/manager/screenings?period=" + period;
            }
            
            Screening screening = screeningOpt.get();
            // 在删除之前先获取需要的信息，避免懒加载问题
            String movieTitle = screening.getMovie().getTitle();
            
            screeningService.deleteScreening(screeningId);
            
            String managerUsername = (String) session.getAttribute("username");
            systemLogService.log("删除场次: " + movieTitle, managerUsername, "DELETE_SCREENING");
            
            redirectAttributes.addFlashAttribute("success", "场次删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除场次失败: " + e.getMessage());
        }
        
        return "redirect:/manager/screenings?period=" + period;
    }
    
    // 销售数据页面
    @GetMapping("/sales-data")
    public String salesData(Model model, HttpSession session) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        // 获取今日销售数据
        Map<String, Object> todayData = calculateSalesDataForPeriod("today");
        model.addAttribute("todayData", todayData);
        
        return "manager/sales-data";
    }
    
    // 零食管理
    @GetMapping("/snacks")
    public String snackManagement(Model model, HttpSession session) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        model.addAttribute("snacks", snackService.getAllSnacks());
        model.addAttribute("lowStockSnacks", snackService.getLowStockSnacks(10));
        return "manager/snacks";
    }
    
    @PostMapping("/snacks/create")
    public String createSnack(@RequestParam String name,
                             @RequestParam double price,
                             @RequestParam int stock,
                             HttpSession session,
                             RedirectAttributes redirectAttributes) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        try {
            snackService.createSnack(name, price, stock);
            redirectAttributes.addFlashAttribute("success", "零食创建成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "创建失败: " + e.getMessage());
        }
        
        return "redirect:/manager/snacks";
    }
    
    @PostMapping("/snacks/add-stock/{id}")
    public String addStock(@PathVariable Long id,
                          @RequestParam int quantity,
                          HttpSession session,
                          RedirectAttributes redirectAttributes) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        try {
            snackService.addStock(id, quantity);
            redirectAttributes.addFlashAttribute("success", "库存添加成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "添加失败: " + e.getMessage());
        }
        
        return "redirect:/manager/snacks";
    }
    
    // 密码管理页面
    @GetMapping("/password-management")
    public String passwordManagement(Model model, HttpSession session) {
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        // 获取所有前台用户
        List<User> receptionists = userService.getUsersByRole("receptionist");
        model.addAttribute("receptionists", receptionists);
        
        return "manager/password-management";
    }
    
    // 修改自身密码（表单提交）
    @PostMapping("/change-own-password")
    public String changeOwnPassword(
            @RequestParam String currentPassword,
            @RequestParam String newPassword,
            @RequestParam String confirmPassword,
            HttpSession session,
            RedirectAttributes redirectAttributes) {
        
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        if (!newPassword.equals(confirmPassword)) {
            redirectAttributes.addFlashAttribute("error", "两次输入的新密码不一致");
            return "redirect:/manager/password-management";
        }
        
        String username = (String) session.getAttribute("username");
        
        if (!userService.verifyPassword(username, currentPassword)) {
            redirectAttributes.addFlashAttribute("error", "当前密码错误");
            return "redirect:/manager/password-management";
        }
        
        userService.updatePassword(username, newPassword);
        
        String managerUsername = (String) session.getAttribute("username");
        systemLogService.log("修改经理密码", managerUsername, "CHANGE_MANAGER_PASSWORD");
        
        redirectAttributes.addFlashAttribute("message", "密码修改成功");
        return "redirect:/manager/password-management";
    }
    
    // 重置前台用户密码（表单提交）
    @PostMapping("/reset-receptionist-password")
    public String resetReceptionistPassword(
            @RequestParam String username,
            HttpSession session,
            RedirectAttributes redirectAttributes) {
        
        if (!checkManagerRole(session)) {
            return "redirect:/login";
        }
        
        Optional<User> targetUserOpt = userService.getUserByUsername(username);
        
        if (!targetUserOpt.isPresent()) {
            redirectAttributes.addFlashAttribute("error", "用户不存在");
            return "redirect:/manager/password-management";
        }
        
        User targetUser = targetUserOpt.get();
        if (!"receptionist".equals(targetUser.getRole())) {
            redirectAttributes.addFlashAttribute("error", "只能重置前台用户密码");
            return "redirect:/manager/password-management";
        }
        
        // 重置密码为123456
        userService.updatePassword(username, "123456");
        userService.setPasswordChangeRequired(username, true);
        
        // 记录日志
        String managerUsername = (String) session.getAttribute("username");
        String logMessage = String.format("重置前台%s的密码", username);
        systemLogService.log(logMessage, managerUsername, "RESET_PASSWORD");
        
        redirectAttributes.addFlashAttribute("message", "密码重置成功，新密码为：123456");
        return "redirect:/manager/password-management";
    }

    // 修改自身密码（AJAX）
    @PostMapping("/change-password")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> changePassword(
            @RequestParam String currentPassword,
            @RequestParam String newPassword,
            HttpSession session) {
        
        Map<String, Object> response = new HashMap<>();
        
        if (!checkManagerRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        String username = (String) session.getAttribute("username");
        
        if (!userService.verifyPassword(username, currentPassword)) {
            response.put("success", false);
            response.put("message", "当前密码错误");
            return ResponseEntity.ok(response);
        }
        
        userService.updatePassword(username, newPassword);
        
        response.put("success", true);
        response.put("message", "密码修改成功");
        
        return ResponseEntity.ok(response);
    }
    
    // 重置前台用户密码（AJAX）
    @PostMapping("/reset-password")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> resetPasswordAjax(
            @RequestParam String username,
            HttpSession session) {
        
        Map<String, Object> response = new HashMap<>();
        
        if (!checkManagerRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        Optional<User> targetUserOpt = userService.getUserByUsername(username);
        
        if (!targetUserOpt.isPresent()) {
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.ok(response);
        }
        
        User targetUser = targetUserOpt.get();
        if (!"receptionist".equals(targetUser.getRole())) {
            response.put("success", false);
            response.put("message", "只能重置前台用户密码");
            return ResponseEntity.ok(response);
        }
        
        // 重置密码为123456
        userService.updatePassword(username, "123456");
        userService.setPasswordChangeRequired(username, true);
        
        // 记录日志
        String managerUsername = (String) session.getAttribute("username");
        String logMessage = String.format("重置前台%s的密码", username);
        systemLogService.log(logMessage, managerUsername, "RESET_PASSWORD");
        
        response.put("success", true);
        response.put("message", "密码重置成功，新密码为：123456");
        
        return ResponseEntity.ok(response);
    }
    
    // 获取所有影片（AJAX）
    @GetMapping("/api/movies")
    @ResponseBody
    public ResponseEntity<?> getAllMovies(HttpSession session) {
        if (!checkManagerRole(session)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "权限不足，请重新登录");
            return ResponseEntity.ok(errorResponse);
        }
        
        List<Movie> movies = movieService.getAllMovies();
        List<Map<String, Object>> movieData = movies.stream().map(movie -> {
            Map<String, Object> movieMap = new HashMap<>();
            movieMap.put("id", movie.getId());
            movieMap.put("title", movie.getTitle());
            movieMap.put("director", movie.getDirector());
            movieMap.put("actors", movie.getActors());
            movieMap.put("synopsis", movie.getSynopsis());
            movieMap.put("duration", movie.getDuration());
            movieMap.put("rating", movie.getRating());
            movieMap.put("status", movie.getStatus());
            return movieMap;
        }).collect(Collectors.toList());
        
        return ResponseEntity.ok(movieData);
    }
    
    // 添加影片（AJAX）
    @PostMapping("/api/movies")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> addMovieAjax(
            @RequestParam String title,
            @RequestParam String director,
            @RequestParam String cast,
            @RequestParam String description,
            @RequestParam int duration,
            @RequestParam double rating,
            HttpSession session) {
        
        Map<String, Object> response = new HashMap<>();
        
        if (!checkManagerRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        Movie movie = new Movie();
        movie.setTitle(title);
        movie.setDirector(director);
        movie.setActors(cast);
        movie.setSynopsis(description);
        movie.setDuration(duration);
        movie.setRating(rating);
        
        movieService.saveMovie(movie);
        
        response.put("success", true);
        response.put("message", "影片添加成功");
        response.put("movie", movie);
        
        return ResponseEntity.ok(response);
    }
    
    // 更新影片（AJAX）
    @PutMapping("/api/movies/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateMovieAjax(
            @PathVariable Long id,
            @RequestParam String title,
            @RequestParam String director,
            @RequestParam String cast,
            @RequestParam String description,
            @RequestParam int duration,
            @RequestParam double rating,
            HttpSession session) {
        
        Map<String, Object> response = new HashMap<>();
        
        if (!checkManagerRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        Optional<Movie> movieOpt = movieService.getMovieById(id);
        if (movieOpt.isPresent()) {
            Movie movie = movieOpt.get();
            movie.setTitle(title);
            movie.setDirector(director);
            movie.setActors(cast);
            movie.setSynopsis(description);
            movie.setDuration(duration);
            movie.setRating(rating);
            
            movieService.saveMovie(movie);
            
            response.put("success", true);
            response.put("message", "影片更新成功");
            response.put("movie", movie);
        } else {
            response.put("success", false);
            response.put("message", "影片不存在");
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 删除影片（AJAX）
    @DeleteMapping("/api/movies/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteMovieAjax(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        if (!checkManagerRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        // 检查是否有正在上映的场次
        List<Screening> screenings = screeningService.getScreeningsByMovieId(id)
            .stream()
            .filter(screening -> screening.getStartTime().isAfter(LocalDateTime.now()))
            .collect(Collectors.toList());
            
        if (!screenings.isEmpty()) {
            response.put("success", false);
            response.put("message", "该影片正在上映，无法删除");
            return ResponseEntity.ok(response);
        }
        
        movieService.deleteMovie(id);
        
        response.put("success", true);
        response.put("message", "影片删除成功");
        
        return ResponseEntity.ok(response);
    }
    
    // 搜索影片（AJAX）
    @GetMapping("/api/movies/search")
    @ResponseBody
    public ResponseEntity<?> searchMoviesAjax(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String director,
            @RequestParam(required = false) String actors,
            HttpSession session) {
        
        if (!checkManagerRole(session)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "权限不足，请重新登录");
            return ResponseEntity.ok(errorResponse);
        }
        
        List<Movie> movies;
        if ((title == null || title.trim().isEmpty()) && 
            (director == null || director.trim().isEmpty()) && 
            (actors == null || actors.trim().isEmpty())) {
            movies = movieService.getAllMovies();
        } else {
            movies = movieService.searchMoviesByMultipleFields(title, director, actors);
        }
        
        List<Map<String, Object>> movieData = movies.stream().map(movie -> {
            Map<String, Object> movieMap = new HashMap<>();
            movieMap.put("id", movie.getId());
            movieMap.put("title", movie.getTitle());
            movieMap.put("director", movie.getDirector());
            movieMap.put("actors", movie.getActors());
            movieMap.put("synopsis", movie.getSynopsis());
            movieMap.put("duration", movie.getDuration());
            movieMap.put("rating", movie.getRating());
            movieMap.put("status", movie.getStatus());
            return movieMap;
        }).collect(Collectors.toList());
        
        return ResponseEntity.ok(movieData);
    }
    
    // 获取场次列表（AJAX）
    @GetMapping("/api/screenings")
    @ResponseBody
    public ResponseEntity<?> getScreenings(
            @RequestParam(defaultValue = "week") String period,
            HttpSession session) {
        
        if (!checkManagerRole(session)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "权限不足，请重新登录");
            return ResponseEntity.ok(errorResponse);
        }
        
        List<Screening> screenings;
        switch (period) {
            case "today":
                screenings = screeningService.getTodayScreenings();
                break;
            case "3days":
                screenings = screeningService.getNext3DaysScreenings();
                break;
            default:
                screenings = screeningService.getUpcomingScreenings();
                break;
        }
        
        List<Map<String, Object>> screeningData = screenings.stream().map(screening -> {
            Map<String, Object> screeningMap = new HashMap<>();
            screeningMap.put("id", screening.getId());
            screeningMap.put("startTime", screening.getStartTime());
            screeningMap.put("price", screening.getPrice());
            screeningMap.put("movieTitle", screening.getMovie().getTitle());
            screeningMap.put("movieId", screening.getMovie().getId());
            screeningMap.put("roomName", screening.getRoom().getName());
            screeningMap.put("roomId", screening.getRoom().getId());
            return screeningMap;
        }).collect(Collectors.toList());
        
        return ResponseEntity.ok(screeningData);
    }
    
    // 添加场次（AJAX）
    @PostMapping("/api/screenings")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> addScreening(
            @RequestParam Long movieId,
            @RequestParam Long roomId,
            @RequestParam String screeningTime,
            @RequestParam BigDecimal price,
            HttpSession session) {
        
        Map<String, Object> response = new HashMap<>();
        
        if (!checkManagerRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            LocalDateTime dateTime = LocalDateTime.parse(screeningTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            
            // 获取电影和放映厅对象
            Optional<Movie> movieOpt = movieService.getMovieById(movieId);
            Optional<ScreeningRoom> roomOpt = screeningRoomService.getRoomById(roomId);
            
            if (!movieOpt.isPresent() || !roomOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "电影或放映厅不存在");
                return ResponseEntity.ok(response);
            }
            
            Screening screening = new Screening();
            screening.setMovie(movieOpt.get());
            screening.setRoom(roomOpt.get());
            screening.setStartTime(dateTime);
            screening.setPrice(price.doubleValue());
            
            // 检查时间冲突
            if (screeningService.hasTimeConflict(screening)) {
                response.put("success", false);
                response.put("message", "该时间段放映厅已有安排");
                return ResponseEntity.ok(response);
            }
            
            screeningService.saveScreening(screening);
            
            response.put("success", true);
            response.put("message", "场次添加成功");
            response.put("screening", screening);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "添加失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 更新场次（AJAX）
    @PutMapping("/api/screenings/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateScreening(
            @PathVariable Long id,
            @RequestParam Long movieId,
            @RequestParam Long roomId,
            @RequestParam String screeningTime,
            @RequestParam BigDecimal price,
            HttpSession session) {
        
        Map<String, Object> response = new HashMap<>();
        
        if (!checkManagerRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        // 检查是否有已售票
        List<Ticket> tickets = ticketService.getTicketsByScreeningId(id);
        if (!tickets.isEmpty()) {
            response.put("success", false);
            response.put("message", "该场次已有售票，无法修改");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Screening> screeningOpt = screeningService.getScreeningById(id);
            if (screeningOpt.isPresent()) {
                Screening screening = screeningOpt.get();
                String originalMovie = screening.getMovie().getTitle();
                
                LocalDateTime dateTime = LocalDateTime.parse(screeningTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                
                Optional<Movie> movieOpt = movieService.getMovieById(movieId);
                Optional<ScreeningRoom> roomOpt = screeningRoomService.getRoomById(roomId);
                
                if (!movieOpt.isPresent() || !roomOpt.isPresent()) {
                    response.put("success", false);
                    response.put("message", "电影或放映厅不存在");
                    return ResponseEntity.ok(response);
                }
                
                screening.setMovie(movieOpt.get());
                screening.setRoom(roomOpt.get());
                screening.setStartTime(dateTime);
                screening.setPrice(price.doubleValue());
                
                screeningService.updateScreening(screening);
                
                // 记录日志
                String managerUsername = (String) session.getAttribute("username");
                Optional<Movie> newMovieOpt = movieService.getMovieById(movieId);
                String newMovie = newMovieOpt.isPresent() ? newMovieOpt.get().getTitle() : "未知影片";
                String logMessage = String.format("修改场次信息：%s，原片名：%s，修改后片名：%s", 
                    dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), originalMovie, newMovie);
                systemLogService.log(logMessage, managerUsername, "UPDATE_SCREENING");
                
                response.put("success", true);
                response.put("message", "场次更新成功");
                response.put("screening", screening);
            } else {
                response.put("success", false);
                response.put("message", "场次不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 删除场次（AJAX）
    @DeleteMapping("/api/screenings/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteScreening(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        if (!checkManagerRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        // 检查是否有已售票
        List<Ticket> tickets = ticketService.getTicketsByScreeningId(id);
        if (!tickets.isEmpty()) {
            response.put("success", false);
            response.put("message", "该场次已有售票，无法删除");
            return ResponseEntity.ok(response);
        }
        
        Optional<Screening> screeningOpt = screeningService.getScreeningById(id);
        if (screeningOpt.isPresent()) {
            Screening screening = screeningOpt.get();
            
            // 在删除之前先获取需要的信息，避免懒加载问题
            String movieTitle = screening.getMovie().getTitle();
            String screeningTimeStr = screening.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            
            screeningService.deleteScreening(id);
            
            // 记录日志
            String managerUsername = (String) session.getAttribute("username");
            String logMessage = String.format("删除场次信息：%s，片名：%s", screeningTimeStr, movieTitle);
            systemLogService.log(logMessage, managerUsername, "DELETE_SCREENING");
            
            response.put("success", true);
            response.put("message", "场次删除成功");
        } else {
            response.put("success", false);
            response.put("message", "场次不存在");
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 自动排片（AJAX）
    @PostMapping("/screenings/auto-schedule")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> autoSchedule(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        if (!checkManagerRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            int scheduledCount = screeningService.autoScheduleScreenings();
            
            response.put("success", true);
            response.put("message", "自动排片完成，共安排 " + scheduledCount + " 个场次");
            response.put("scheduledCount", scheduledCount);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "自动排片失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 获取销售数据（AJAX）
    @GetMapping("/api/sales-data")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getSalesData(
            @RequestParam(defaultValue = "today") String period,
            HttpSession session) {
        
        if (!checkManagerRole(session)) {
            return ResponseEntity.status(401).build();
        }
        
        Map<String, Object> salesData = calculateSalesDataForPeriod(period);
        return ResponseEntity.ok(salesData);
    }
    
    // 计算指定时期的销售数据
    private Map<String, Object> calculateSalesDataForPeriod(String period) {
        List<Order> orders;
        
        switch (period) {
            case "week":
                orders = orderService.getWeekOrders();
                break;
            case "month":
                orders = orderService.getMonthOrders();
                break;
            default:
                orders = orderService.getTodayOrders();
                break;
        }
        
        Map<String, Object> salesData = new HashMap<>();
        
        // 计算基础统计数据
        int totalTickets = (int) orders.stream()
            .filter(order -> !order.isRefunded())
            .count();
            
        double totalSales = orders.stream()
            .filter(order -> !order.isRefunded())
            .mapToDouble(Order::getAmount)
            .sum();
            
        int totalRefunds = (int) orders.stream()
            .filter(Order::isRefunded)
            .count();
            
        double totalRefundAmount = orders.stream()
            .filter(Order::isRefunded)
            .mapToDouble(Order::getAmount)
            .sum();
        
        salesData.put("totalTickets", totalTickets);
        salesData.put("totalSales", totalSales);
        salesData.put("totalRefunds", totalRefunds);
        salesData.put("totalRefundAmount", totalRefundAmount);
        
        // 计算比率
        int totalOrders = orders.size();
        double ticketRate = totalOrders > 0 ? (double) totalTickets / totalOrders * 100 : 0;
        double refundRate = totalOrders > 0 ? (double) totalRefunds / totalOrders * 100 : 0;
        
        salesData.put("ticketRate", Math.round(ticketRate * 100.0) / 100.0);
        salesData.put("refundRate", Math.round(refundRate * 100.0) / 100.0);
        
        // 按场次统计详情
        Map<Long, Map<String, Object>> screeningStatsMap = new HashMap<>();
        for (Order order : orders) {
            Long screeningId = order.getScreening().getId();
            screeningStatsMap.computeIfAbsent(screeningId, k -> {
                Map<String, Object> stats = new HashMap<>();
                Screening screening = order.getScreening();
                stats.put("movieTitle", screening.getMovie().getTitle());
                stats.put("screeningTime", screening.getStartTime().format(DateTimeFormatter.ofPattern("MM-dd HH:mm")));
                stats.put("roomName", screening.getRoom().getName());
                stats.put("price", screening.getPrice());
                stats.put("ticketsSold", 0);
                stats.put("sales", 0.0);
                stats.put("refunds", 0);
                stats.put("refundAmount", 0.0);
                return stats;
            });
            
            Map<String, Object> stats = screeningStatsMap.get(screeningId);
            if (order.isRefunded()) {
                stats.put("refunds", (Integer) stats.get("refunds") + 1);
                stats.put("refundAmount", (Double) stats.get("refundAmount") + order.getAmount());
            } else {
                stats.put("ticketsSold", (Integer) stats.get("ticketsSold") + 1);
                stats.put("sales", (Double) stats.get("sales") + order.getAmount());
            }
        }
        
        salesData.put("screeningDetails", new ArrayList<>(screeningStatsMap.values()));
        
        // 热门影片统计
        Map<String, Integer> movieTicketCount = new HashMap<>();
        for (Order order : orders) {
            if (!order.isRefunded()) {
                String movieTitle = order.getScreening().getMovie().getTitle();
                movieTicketCount.put(movieTitle, movieTicketCount.getOrDefault(movieTitle, 0) + 1);
            }
        }
        
        List<Map<String, Object>> popularMovies = movieTicketCount.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
            .limit(5)
            .map(entry -> {
                Map<String, Object> movie = new HashMap<>();
                movie.put("title", entry.getKey());
                movie.put("ticketsSold", entry.getValue());
                return movie;
            })
            .collect(Collectors.toList());
        
        salesData.put("popularMovies", popularMovies);
        
        return salesData;
    }
    
}